import { createRouter, createWebHashHistory } from 'vue-router';
import { closeAll } from 'src/utils';
import dynamicRoutes from 'src/router/dynamicRoutes';
import { clearPending } from 'src/plugins/http/cancelToken';
import { useStore } from 'src/pinia';
import { getCache, keys } from 'src/pinia/common';
import NProgress from 'nprogress';
import base from './base';
import whiteRoutes from './whiteRoutes';
import 'nprogress/nprogress.css';

const router = createRouter({
    'isAddDynamicMenuRoutes': false,
    'history': createWebHashHistory(),
    'routes': base
});
const np = {
    start() {
        NProgress.start();
    },
    done(to, from) {
        NProgress.done(true);
        if (to.name === 'Login') { router.options.isAddDynamicMenuRoutes = false; }
        return true;
    },
    error() {
        return { 'name': 'Login' };
    }
};
const addDynamicRoutes = (m, cb) => {
    let menus = m || (getCache(keys.user)?.menus || []);
    if (menus && menus.length) {
        const getDynamicRoutes = () => {
            const dynamic = [];
            try {
                for (const menu of menus) {
                    const matchRoute = dynamicRoutes.find(d => d.path === menu.path);
                    if (matchRoute) { dynamic.push(matchRoute); }
                }
            } catch (e) {
                console.log(e);
            }
            return dynamic;
        };
        const dynamicRs = getDynamicRoutes();
        dynamicRs.forEach(r => {
            if (!router.hasRoute(r.name)) {
                router.addRoute('Layout', r);
            }
        });
        if (cb) { cb(); }
    }
};
addDynamicRoutes(null);
NProgress.configure({ showSpinner: false });

router.beforeEach(async (to, from) => {
    np.start();
    const { user } = useStore();
    const { token } = user.userInfo;
    document.title = to.name;
    return np.done(to, from);
    // if (whiteRoutes.includes(to.path)) { return np.done(to, from); }
    // if (token) {
    //     if (router.options.isAddDynamicMenuRoutes) { return np.done(to, from); }
    //     try {
    //         const res = { data: [] };
    //         user.$patch({ 'menus': res.data });
    //         addDynamicRoutes(res.data, () => {
    //             router.options.isAddDynamicMenuRoutes = true;
    //             return np.done(to, from);
    //         });
    //     } catch (e) {
    //         return np.done(to, from);
    //     }
    // } else {
    //     return np.error();
    // }
});
router.afterEach((to, from) => {
    clearPending(); closeAll();
    return np.done(to, from);
});

export function setupRoute(app) {
    app.use(router);
}
